<template>
  <div class="h-full">
    <SearchContainer @reset="() => formRef.resetFields()" @search="getData">
      <a-form ref="formRef" class="form-style-flex" :model="formState">
        <a-form-item name="pyjm" class="w-80 mr-2">
          <a-input v-model:value="formState.pyjm" placeholder="套餐名称/项目名称" />
        </a-form-item>
        <a-form-item label="检验大类" class="w-80">
          <a-select v-model:value="formState.lisCategroyId" placeholder="请选择" allow-clear @change="onChangeCate">
            <a-select-option v-for="item in categoryList" :key="item" :value="item.categoryCode">{{ item.categoryName }}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </SearchContainer>
    <div class="flex mt-2">
      <a-card class="mr-2">
        <div class="mb-2">
          <a-button class="mr-2" type="primary" @click="onClickAdd()"> 新增 </a-button>
          <a-button> 导出 </a-button>
        </div>
        <BaseTable
          fill
          :loading="loading"
          column-code="000197"
          :data-source="tableData"
          bordered
          row-key="id"
          :pagination="pagination"
          :custom-row="onClickRow"
          :row-class-name="(record) => (record.id === selectedKey ? 'selected-row' : '')"
          class="w-[1100px]"
        >
          <template #bodyCell="{ column, index, record }">
            <template v-if="column.dataIndex === 'xh'">
              {{ index + 1 }}
            </template>
            <template v-if="column.dataIndex === 'action'">
              <BaseButton type="link" size="small" @click="onClickAdd(record)">修改</BaseButton>
              <a-divider type="vertical" />
              <BaseButton confirm-text="确认作废？" type="link" danger size="small" @click="onClickCancel(record)">作废</BaseButton></template
            >
          </template>
        </BaseTable>
      </a-card>
      <div class="flex flex-col flex-1 overflow-hidden">
        <a-card class="flex-1 overflow-auto">
          <div>套餐明细：{{ selectedName }}</div>
          <div class="my-2">
            <a-space>
              <!-- <a-select ref="select" v-model:value="categoryCode" class="w-52" placeholder="请选择" @change="onChangeCate">
                <a-select-option v-for="item in categoryList" :key="item" :value="item.categoryCode">{{ item.categroyName }}</a-select-option>
              </a-select> -->
              <a-select ref="select" v-model:value="instrumentId" class="w-52" placeholder="请选择" @change="getDataProject">
                <a-select-option v-for="item in instrumentList" :key="item" :value="item.id">{{ item.instrumentTypeName }}</a-select-option>
              </a-select>
            </a-space>
          </div>
          <BaseTable
            :loading="loadingProject"
            column-code="000194"
            fill
            :data-source="tableDataProject"
            bordered
            row-key="itemCode"
            :row-selection="rowSelection"
            :extra-height="50"
          >
            <template #bodyCell="{ column, index }">
              <template v-if="column.dataIndex === 'xh'">
                {{ index + 1 }}
              </template>
            </template>
          </BaseTable>
          <div class="flex justify-end mt-3">
            <a-button type="primary" @click="onSave"> 保存 </a-button>
          </div>
        </a-card>
      </div>
    </div>
    <Edit v-model:open="editOpen" :row-data="rowData" @success="getData" />
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import SearchContainer from '@/components/SearchContainer'
import BaseTable from '@/components/BaseTable'
import Edit from './components/Edit'

const selectedName = ref('')
const categoryCode = ref(null)
const instrumentId = ref(null)
const selectedKey = ref(null)
const editOpen = ref(false)
const formRef = ref(null)
const formState = ref({})
const rowData = ref({})
const defaultCheckedKeys = ref([])
const categoryList = ref([])
const instrumentList = ref([])

const rowSelection = ref({
  checkStrictly: true,
  selectedRowKeys: defaultCheckedKeys,
  onChange: (selectedRowKeys) => {
    defaultCheckedKeys.value = selectedRowKeys
  }
})

const { loading, pagination, getData, tableData } = useTable({
  url: '/lis/LisPackage/getLisPackageList',
  params: formState.value,
  immediate: true,
  formatResult: (result) => {
    selectedKey.value = selectedKey.value || result[0]?.id
    selectedName.value = selectedName.value || result[0]?.packageName
    getCategoryList()
    return result
  }
})

const {
  loading: loadingProject,
  tableData: tableDataProject,
  getData: getDataProject
} = useTable({
  url: '/lis/LisPackage/getLisPackageDetailList',
  formatParams: () => {
    return {
      instrumentTypeId: instrumentId.value || '',
      packageId: selectedKey.value || ''
    }
  },
  formatResult: (result) => {
    defaultCheckedKeys.value = result.map((i) => {
      if (i.chek === 1) return i.itemCode
    })
    return result
  }
})

const getCategoryList = async () => {
  const { code, data, msg } = await post('/lis/InstrumentType/getLisCategoryList')
  if (code !== 0) return message.error(msg)
  categoryList.value = data
  categoryCode.value = categoryCode.value || data[0]?.categoryCode
  // formState.value.lisCategroyId = formState.value.lisCategroyId || data[0]?.categoryCode
  // getInstrumentTypeList()
}

const getInstrumentTypeList = async () => {
  const { code, data, msg } = await post('/lis/InstrumentType/getInstrumentTypeList', {
    pageNum: 1,
    pageSize: 999,
    pyjm: '',
    categoryCode: categoryCode.value
  })
  if (code !== 0) return message.error(msg)
  instrumentList.value = data
  instrumentId.value = data[0]?.id
  if (tableData.value.length) {
    getDataProject()
  } else {
    tableDataProject.value = []
  }
}

const onClickAdd = (row = {}) => {
  rowData.value = { ...row }
  editOpen.value = true
}

const onClickCancel = async (row) => {
  const { code, msg } = await post('/lis/LisPackage/doDelLisPackage', { ...row, lisCategroyId: formState.value.lisCategroyId })
  if (code !== 0) return message.error(msg)
  message.success(msg)
  getData()
}

const onClickRow = (row) => {
  return {
    onClick: () => {
      selectedKey.value = row.id
      selectedName.value = row.packageName
      getDataProject()
    }
  }
}

const onChangeCate = async (val) => {
  categoryCode.value = val
  await getData()
  val && (await getInstrumentTypeList())
}

const onSave = async () => {
  if (!formState.value.lisCategroyId) return message.error('请选择检验大类')
  const { code, msg } = await post('/lis/LisPackage/doSaveLisPackageDetail', {
    lisCategroyId: categoryCode.value,
    lisInstrumentTypeId: instrumentId.value,
    lisOrderRelationList: defaultCheckedKeys.value.filter((i) => i !== null),
    packageId: selectedKey.value
  })
  if (code !== 0) return message.error(msg)
  message.success(msg)
  getData()
}

onMounted(() => {
  getCategoryList()
})
</script>
